#include "transcalcwindow.h"
#include "ui_transcalcwindow.h"

TranscalcWindow::TranscalcWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::TranscalcWindow)
{
    ui->setupUi(this);
    ui->resultPanel->setTextBackgroundColor(Qt::white);
    ui->resultPanel->setFontFamily("Sans Serif");
    ui->resultPanel->setFontPointSize(10.0f);
}

TranscalcWindow::~TranscalcWindow()
{
    delete ui;
}

void TranscalcWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void TranscalcWindow::on_formulaEntry_returnPressed()
{
    QByteArray formula = ui->formulaEntry->text().toUtf8();
    StringRef expr = StringRef::fromMutable(formula.data(), formula.length());
    StringRef result = NULL_STRING;
    bool error = false;
    try
    {
        result = calc.calculateThrowError(expr);
        error = false;
    }
    catch(StringRef message)
    {
        result = message;
        error = true;
    }

    AutoDeleteArray<wchar_t> buf = new wchar_t[result.getLength()+1];
    utf8cpy(buf, result.getLength()+1, *result);
    ui->resultPanel->setTextColor(error ? Qt::red : Qt::black);
    ui->resultPanel->append(QString::fromWCharArray(buf.getPointer()));
    ui->formulaEntry->selectAll();
}
